<template>

    <div class="page-100 login-register-part">
        <img src="../../assets/logo.jpg" class="img-logo" alt="">
        <yd-cell-item style="padding-bottom: 20px">
            <img  slot="left" class="login-img" src="../../assets/loginxingyenum.png">
            <input @blur="checkMobileBlur" slot="right" type="number" placeholder="账号姓名" v-model="mobile" maxlength="11"
                   oninput="if (value.length>11) value=value.slice(0,11)" >
        </yd-cell-item>
        <yd-cell-item>
            <img  slot="left" class="login-img" src="../../assets/loginpassword.png">
            <yd-input slot="right" type="password" placeholder="密码" v-model="password" maxlength="20"
                      :minlength="6" ></yd-input>
        </yd-cell-item>
        <div class="button-group-part">
            <div class="button-register-reset-part">
                <p class="blue-color" href="javascript:;" @click="gotoRegisterClick">注册或激活账号</p>
                <p class="blue-color" @click="gotoReset">忘记密码</p>
            </div>

            <yd-button size="large" type="primary" @click.native="handleClick" style="background-color:#3cc8a8;color:white;height: 40px">确定</yd-button>

        </div>
    </div>
</template>

<script>
    let Base64 = require('js-base64').Base64;
    import axios from 'axios'
    import city from "../../../city.json"
    import {checkMobile, loginCustomer, getAccessToken, getWeiXinConfig4Url, loginByOpenId} from "../../pcof/post";
    import wechatOperation from '../../wechatOpeartion';
    import {
        password,
        loginWXStatus,
        autoLoginState,
        mainUrl,
        authToken,
        loginWechatCode,
        openId,
        mobile,
        userInfoData,
        qn_domain,
        qn_scope,
        qn_ak,
        qn_sk,
        wxAccessToken
    } from '../../globalVariables'
    import FromList from "@/components/examineComponent.vue";


    export default {
        name: "loginPhone",
        data() {
            return {
                start1: false,

                mobile: JSON.parse(localStorage.getItem(mobile)),
                password: '',
                userState: '0',//注册或激活账号 userState 0 是需要注册 1是需要激活 2是重置密码
                loginUserState: '0', //用户状态：0-正常，1-审批中，3-被拒绝 登录之后
                phoneCode: '200',


            };
        },

        async created() {
            if (localStorage.getItem(openId) === null || localStorage.getItem(openId) === '') {
                console.log('openid is null');
                var wxCode = localStorage.getItem(loginWechatCode);
                if (wxCode != null) {
                    console.log('wxCode is not null');
                    var accessTokenResponse = await getAccessToken(wxCode);
                    if (accessTokenResponse.data.code === 200) {
                        localStorage.setItem(openId, accessTokenResponse.data.token.openid);
                        localStorage.setItem(wxAccessToken, accessTokenResponse.data.token.accessToken);
                        //自动登录
                        if (localStorage.getItem(userInfoData) === null || localStorage.getItem(userInfoData) === '') {
                        } else {
                            var loginResponse = await loginByOpenId(
                                JSON.parse(localStorage.getItem(userInfoData)).mobile,
                                localStorage.getItem(openId));
                            localStorage.setItem(authToken, loginResponse.data.authtoken);

                            if (loginResponse.data.code === 200) {
                                //保存用户信息 将object数据转换为 string 存入localStorage
                                localStorage.setItem(userInfoData, JSON.stringify(loginResponse.data.data));
                                localStorage.setItem(qn_domain, loginResponse.data.data.qn_domain);
                                localStorage.setItem(qn_scope, loginResponse.data.data.qn_scope);
                                localStorage.setItem(qn_ak, loginResponse.data.data.qn_ak);
                                localStorage.setItem(qn_sk, loginResponse.data.data.qn_sk);
                                //用法将string 转为 object 再取值
                                // console.log(JSON.parse(localStorage.getItem(userInfoData)).province);
                                //用户状态：0-正常,1-待审核,2-自动注册(未激活),3-被拒绝,4-已删除
                                this.$router.push({name: 'homeDetail', params: {mobile: this.mobile}});
                            } else if (loginResponse.data.code === 501) {
                                console.log(response.data.msg);
                            }

                        }
                    } else {

                    }
                } else {
                    console.log("wxCode is null")
                }
            } else {
                console.log('openid is not null');
                // var response = await loginByOpenId(localStorage.getItem(openId));
                if (localStorage.getItem(userInfoData) === null || localStorage.getItem(userInfoData) === '') {
                } else {
                    var response = await loginByOpenId(
                        JSON.parse(localStorage.getItem(userInfoData)).mobile,
                        localStorage.getItem(openId));

                    if (response.data.code === 200) {
                        localStorage.setItem(authToken, response.data.authtoken);
                        //保存用户信息 将object数据转换为 string 存入localStorage
                        localStorage.setItem(userInfoData, JSON.stringify(response.data.data));
                        localStorage.setItem(qn_domain, response.data.data.qn_domain);
                        localStorage.setItem(qn_scope, response.data.data.qn_scope);
                        localStorage.setItem(qn_ak, response.data.data.qn_ak);
                        localStorage.setItem(qn_sk, response.data.data.qn_sk);
                        //用法将string 转为 object 再取值
                        // console.log(JSON.parse(localStorage.getItem(userInfoData)).province);
                        //用户状态：0-正常,1-待审核,2-自动注册(未激活),3-被拒绝,4-已删除
                        this.$router.push({name: 'homeDetail', params: {mobile: this.mobile}});
                    } else if (response.data.code === 800) {
                        this.mobile = JSON.parse(localStorage.getItem(userInfoData)).mobile;
                        this.password = Base64.decode(localStorage.getItem(password));
                        if (this.password === null || this.password === '' || this.password === undefined) {

                        } else {
                            this.loginCustomerFunc();
                        }

                    } else if (response.data.code === 501) {
                        console.log(response.data.msg);
                    }
                }
            }

            if (localStorage.getItem(loginWXStatus) == 2) {
                //正式环境使用
                var url = localStorage.getItem(mainUrl);
                if (url != null) {
                    var response = await getWeiXinConfig4Url(url);
                    wechatOperation.weInit(response.data.data)
                }
            }

        },
        methods: {

            /**注册或激活账号*/
            gotoRegisterClick() {
                //注册或激活账号 userState 0 是需要注册 1是需要激活 2是重置密码

                this.$router.push({name: 'loginResetPwd', params: {userState: this.userState}});

            },
            /**忘记密码*/
            gotoReset() {
                //忘记密码
                this.$router.push({name: 'loginResetPwd', params: {userState: '2'}});

            },
            async loginCustomerFunc() {
                this.$dialog.loading.open('登录中...');
                localStorage.setItem(password, Base64.encode(this.password));
                var response = await loginCustomer(this.mobile, this.password, localStorage.getItem(openId));
                if (response.data.code === 200) {
                    if (response.data.data.openid === null || response.data.data.openid === '') {

                    } else {
                        localStorage.setItem(openId, response.data.data.openid);
                    }
                    this.$dialog.loading.close();
                    localStorage.removeItem(mobile);
                    this.loginUserState = response.data.data.state;
                    localStorage.setItem(autoLoginState, 1);
                    // localStorage.setItem('mobile',this.mobile);
                    //保存用户信息 将object数据转换为 string 存入localStorage
                    localStorage.setItem(userInfoData, JSON.stringify(response.data.data));
                    localStorage.setItem(qn_domain, response.data.data.qn_domain);
                    localStorage.setItem(qn_scope, response.data.data.qn_scope);
                    localStorage.setItem(qn_ak, response.data.data.qn_ak);
                    localStorage.setItem(qn_sk, response.data.data.qn_sk);
                    //用法将string 转为 object 再取值
                    // console.log(JSON.parse(localStorage.getItem(userInfoData)).province);
                    //用户状态：0-正常,1-待审核,2-自动注册(未激活),3-被拒绝,4-已删除
                    if (this.loginUserState === '0') {
                        //0:正常
                        localStorage.removeItem(mobile);
                        this.$router.push({name: 'homeDetail', params: {mobile: this.mobile}});
                    } else if (this.loginUserState === '1' || this.loginUserState === '3') {

                        this.$router.push({name: 'loginCheckinfo', params: {loginUserState: this.loginUserState}});

                    } else if (this.loginUserState === '2') {
                        this.$router.push({name: 'loginResetPwd', params: {userState: this.userState}});
                    }
                } else {
                    this.$dialog.loading.close();
                    console.log(response.data.msg);
                    this.$dialog.toast({
                        mes: response.data.msg,
                        timeout: 1500
                    });
                }
            },
            /**登录按钮事件*/
            async handleClick() {

                if (this.mobile === null || this.mobile === '') {
                    this.$dialog.toast({
                        mes: '请输入手机号!',
                        timeout: 1500
                    });
                    return;
                }
                if (this.mobile.length < 11) {
                    this.$dialog.toast({
                        mes: '手机输入有误！',
                        timeout: 1500
                    });
                    return;
                }


                if (this.password === null || this.password === '') {
                    this.$dialog.toast({
                        mes: '请输入密码!',
                        timeout: 1500
                    });
                    return;
                }
                // var exp=/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/;
                //
                // if(!exp.test(this.password))
                // {
                //     this.$dialog.toast({
                //         mes: '请输入8-20位密码，密码必须同时包含字母和数字',
                //         timeout: 1500
                //     });
                //     return;
                // }
                //编程跳转写在一个函数里面，通过click等方法来触发
                var response = await checkMobile(this.mobile);
                localStorage.setItem(authToken, response.data.authtoken);
                this.phoneCode = response.data.code;
                console.log(this.phoneCode);

                if (this.phoneCode === 200) {

                    this.loginCustomerFunc();
                } else if (this.phoneCode === 201) {
                    // localStorage.setItem('mobile',this.mobile);
                    //注册或激活账号 userState 0 是需要注册 1是需要激活 2是重置密码

                    this.userState = '0';
                    //1:未注册
                    this.$dialog.confirm({
                        title: '',
                        mes: '该手机号尚未注册。',
                        opts: [
                            {
                                txt: '确定',
                                color: true,
                                callback: () => {
                                    //注册或激活账号 userState 0 是需要注册 1是需要激活 2是重置密码
                                    this.$router.push({name: 'loginResetPwd', params: {userState: this.userState}});
                                }
                            }
                        ]
                    });
                } else if (this.phoneCode === 202) {
                    this.userState = '1';
                    // localStorage.setItem('mobile',this.mobile);
                    this.$dialog.confirm({
                        title: '',
                        mes: '该账号尚未激活，请先激活账号。',
                        opts: [
                            {
                                txt: '确定',
                                color: true,
                                callback: () => {
                                    //注册或激活账号 userState 0 是需要注册 1是需要激活 2是重置密码
                                    this.$router.push({
                                        name: 'loginResetPwd',
                                        params: {userState: this.userState, moblie: this.moblie}
                                    });
                                }
                            }
                        ]
                    });
                } else {
                    this.$dialog.loading.close();
                    this.$dialog.toast({
                        mes: response.data.msg,
                        timeout: 1500
                    });
                }

            },
            /**手机号码输入框失去焦点事件*/
            async checkMobileBlur() {


                if (this.mobile === null || this.mobile === '') {
                    this.$dialog.toast({
                        mes: '请输入手机号!',
                        timeout: 1500
                    });
                    return;
                }
                if (this.mobile.length < 11) {
                    this.$dialog.toast({
                        mes: '手机格式错误！',
                        timeout: 1500
                    });
                    return;
                }


                //code 200-正常，201-未注册 202-未激活 // 校验手机号
                //失去焦点事件
                // 请求检查手机号接口获取authtoken
                var response = await checkMobile(this.mobile);
                localStorage.setItem(authToken, response.data.authtoken);
                this.phoneCode = response.data.code;
                console.log(this.phoneCode);

                if (this.phoneCode === 200) {

                } else if (this.phoneCode === 201) {
                    // localStorage.setItem('mobile',this.mobile);
                    //注册或激活账号 userState 0 是需要注册 1是需要激活 2是重置密码
                    localStorage.setItem(mobile, JSON.stringify
                    (this.mobile));
                    this.userState = '0';
                    //1:未注册
                    this.$dialog.confirm({
                        title: '',
                        mes: '该手机号尚未注册。',
                        opts: [
                            {
                                txt: '确定',
                                color: true,
                                callback: () => {
                                    //注册或激活账号 userState 0 是需要注册 1是需要激活 2是重置密码
                                    this.$router.push({name: 'loginResetPwd', params: {userState: this.userState}});
                                }
                            }
                        ]
                    });
                } else if (this.phoneCode === 202) {
                    this.userState = '1';
                    localStorage.setItem(mobile, JSON.stringify
                    (this.mobile));
                    this.$dialog.confirm({
                        title: '',
                        mes: '该账号尚未激活，请先激活账号。',
                        opts: [
                            {
                                txt: '确定',
                                color: true,
                                callback: () => {
                                    //注册或激活账号 userState 0 是需要注册 1是需要激活 2是重置密码
                                    this.$router.push({
                                        name: 'loginResetPwd',
                                        params: {userState: this.userState, moblie: this.moblie}
                                    });
                                }
                            }
                        ]
                    });
                } else if (this.phoneCode === 500) {
                    this.$dialog.toast({
                        mes: response.data.msg,
                        timeout: 1500
                    });
                }

            },
        }
    };
</script>
<style lang='scss'>

    @import "./login.scss";

    .img-logo {
        width: 1.1rem;
        height: 1.1rem;
        margin-bottom: 0.8rem;
    }

    .after-btn-left-p {
        text-align: left;
        color: #3cc8a8;
        float: left;
        margin: 10px;
        font-size: 0.25rem;
    }

    .after-btn-right-p {
        text-align: right;
        color: #3cc8a8;
        float: right;
        margin-top: 10px;
        font-size: 0.25rem;
    }
</style>
